//
//  TOSearchViewController.m
//  B段项目
//
//  Created by dllo on 15/12/24.
//  Copyright © 2015年 张智超. All rights reserved.
//

#import "TOSearchViewController.h"
#import "TOSearchTableCell.h"
#import "TOSearchListModel.h"
#import "TOSearchDetailModel.h"
#import "TOTools.h"
#import "ZZCWebViewController.h"

@interface TOSearchViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchResultsUpdating>

@property (nonatomic, retain)UITableView *searchTableView;
@property (nonatomic, retain)NSMutableArray *listArray; /**< 开始搜索的界面数组 */
@property (nonatomic, retain)UIButton *btnAccessoryView;
@property (nonatomic, retain)NSMutableArray *searchArray; /**< 实时搜索的界面数组 */
@property (nonatomic, retain)UISearchController *mysearchController;
@property (nonatomic, copy)NSString *searchString;
@property (nonatomic, retain)NSMutableArray *searchListArray; /**< 点击搜索的界面数组 */
@property (nonatomic, assign)BOOL selected;
@property (nonatomic, assign)NSInteger nextPage;
@property (nonatomic, assign)BOOL isUpLoad;

@end

@implementation TOSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(leftBarButtonItem)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    [self.navigationController.navigationBar setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
    
    [self createSearchBar];
    [self createTableView];
    [self getRecommendData];
}

#pragma mark - 设置searchBar
-(void)createSearchBar
{
    self.mysearchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.mysearchController.searchResultsUpdater = self;
    self.mysearchController.searchBar.delegate = self;
    // 设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.mysearchController.dimsBackgroundDuringPresentation = NO;
    // 设置点击搜索框时候隐藏导航栏
    self.mysearchController.hidesNavigationBarDuringPresentation = NO;
    
    self.navigationItem.titleView = self.mysearchController.searchBar;
    
    //    :设置searchBar位置自适应
    [self.mysearchController.searchBar sizeToFit];
    [self.mysearchController.searchBar setPlaceholder:@"搜索"];
    
}

#pragma mark - 创建TableView
-(void)createTableView
{
    //TableView
    self.searchTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    [self.view addSubview:self.searchTableView];
    
    
    //注册
    [self.searchTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.searchTableView registerClass:[TOSearchTableCell class] forCellReuseIdentifier:@"TOSearchTableCell"];
    
}

#pragma mark - 推荐的数据请求
-(void)getRecommendData
{
    self.listArray = [NSMutableArray array];
    //推荐的数据请求
    NSString *url = @"http://api2.pianke.me/search/hotlist";
    NSString *body = @"auth=&client=1&deviceid=0F79DA7D-8DF2-416D-B3C3-7BD488A50BDD&version=3.0.6";
    [ZYTools postUrl:url body:body result:ZYJSON requestStyle:ZYRequestString headerFile:nil success:^(id result) {
        NSMutableArray *array = [result objectForKey:@"data"];
        for (NSMutableDictionary *dic in array) {
            TOSearchListModel
            *searchListM = [[TOSearchListModel alloc] init];
            [searchListM setValuesForKeysWithDictionary:dic];
            [self.listArray addObject:searchListM];
        }
        [self.searchTableView reloadData];
        
    } failure:^(NSError *error) {
        
        
    }];

}

#pragma mark - tableView协议方法

#pragma mark  设置区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

#pragma mark 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.selected == NO) {
        
        if (self.searchArray.count == 0) {
            return self.listArray.count;
        } else {
            return self.searchArray.count;
        }
    } else {
        return self.searchListArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    static NSString *cellIdntifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdntifier];
    
    // 取消点击cell的效果(在设置cell里写)
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (self.selected == NO) {
        if (self.searchArray.count == 0) {
            TOSearchListModel *seaListModel = [self.listArray objectAtIndex:indexPath.row];
            cell.textLabel.text = seaListModel.title;
            return cell;
        } else {
            cell.textLabel.text = [self.searchArray objectAtIndex:indexPath.row];
            
            self.searchListArray = [NSMutableArray array];
            
#pragma mark  设置关键字高亮
            
            NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc]initWithString:cell.textLabel.text];
            NSRange rangeStr =  [cell.textLabel.text rangeOfString:self.searchString];
            [attribute setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor redColor]} range:rangeStr];
            cell.textLabel.attributedText = attribute;
            return cell;
            
        }
        
    } else {
        
        TOSearchTableCell *searchCell = [tableView dequeueReusableCellWithIdentifier:@"TOSearchTableCell"];
        searchCell.selectionStyle = UITableViewCellSelectionStyleNone;

        TOSearchDetailModel *seaDetailModel = [self.searchListArray objectAtIndex:indexPath.row];
        searchCell.searchDetail = seaDetailModel;
        searchCell.searchStr = self.searchString;
      
        
        
        return searchCell;
    }
    
}


#pragma mark - 设置section表头标题
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (self.selected == 0) {
        if (self.searchArray.count == 0) {
            return @"大家为您推荐";
        } else {
            return @"你可能在找";
        }
    } else {
        return @"你想要的故事";
    }
}


#pragma mark - 设置表头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return self.searchTableView.frame.size.height / 9.5;
}



#pragma mark - 设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selected == 0) {
        return self.searchTableView.frame.size.height / 11;
    } else {
     
        return WIDTH/2.5;
    }
}


#pragma mark - 触摸cell触发方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.selected == NO) {
        
        TOSearchListModel *searchList = [self.listArray objectAtIndex:indexPath.row];
        if (self.searchArray.count == 0) {
            
            if (searchList.playInfo.allKeys.count == 0) {
                
                // 跳转到阅读web详情
                ZZCWebViewController *detailWebVC = [[ZZCWebViewController alloc] init];
                detailWebVC.contentId = searchList.contentid;
                [self.navigationController pushViewController:detailWebVC animated:YES];
            } else {
                
                [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"SearchPush"];
                [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"HomePush"];
                
                // 跳转到播放器
                NSString *tingId = [searchList.playInfo objectForKey:@"tingid"];
                [ZZCMusicPlayerViewController shareMusicPlayerViewController]._id = tingId;
                
                [self.navigationController pushViewController:[ZZCMusicPlayerViewController shareMusicPlayerViewController] animated:YES];
            }
        } else {
            self.selected = !self.selected;
            self.searchString = [self.searchArray objectAtIndex:indexPath.row];
            [self.searchTableView reloadData];
        }
    } else {
        
        //跳到阅读web详情
        TOSearchDetailModel *searchDetail = [self.searchListArray objectAtIndex:indexPath.row];;
        ZZCWebViewController *detailVC = [[ZZCWebViewController alloc] init];
        detailVC.contentId = searchDetail.contentid;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
    
}

#pragma mark - 点击键盘中的搜索按钮, 时执行
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    self.navigationItem.hidesBackButton = NO;
    
    self.searchString = [searchBar text];
    
    [searchBar resignFirstResponder];
    
    
    
}

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    // 用字符串接收搜索框中输入的字符串
    self.searchArray = [NSMutableArray array];

    self.searchString = searchController.searchBar.text;
    
    
    [self getAFNetWorkingDataWithSearchString:searchController.searchBar.text];
    
    if (self.selected) {
        self.selected = !self.selected;
    }
    
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    self.searchString = [self.mysearchController.searchBar text];
    
    [self getAFNetWorkingDataDetail];
    self.selected = !self.selected;
    
}


#pragma mark - 返回按钮方法
-(void)leftBarButtonItem
{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}


- (void)getAFNetWorkingDataWithSearchString:(NSString *)string{
    
    NSString *url = @"http://api2.pianke.me/search/suggest";
    NSString *body = [NSString stringWithFormat:@"auth=&client=1&deviceid=0F79DA7D-8DF2-416D-B3C3-7BD488A50BDD&keyword=%@&version=3.0.6", string];
    [ZYTools postUrl:url body:body result:ZYJSON requestStyle:ZYRequestString headerFile:nil success:^(id result) {
        
        NSMutableArray *array = [result objectForKey:@"data"];
        for (NSMutableDictionary *dic in array) {
            [self.searchArray addObject:[dic objectForKey:@"name"]];
        }
        [self.searchTableView reloadData];
    } failure:^(NSError *error) {
        
        
    }];
    
}

#pragma mark - 数据请求
- (void)getAFNetWorkingDataDetail{
    
    self.searchListArray = [NSMutableArray array];
    NSString *url = @"http://api2.pianke.me/search/get";
    NSString *body = [NSString stringWithFormat:@"auth=&client=1&deviceid=0F79DA7D-8DF2-416D-B3C3-7BD488A50BDD&keyword=%@&limit=10&start=%ld&type=content&version=3.0.6", self.searchString, self.nextPage];
    
    [ZYTools postUrl:url body:body result:ZYJSON requestStyle:ZYRequestString headerFile:nil success:^(id result) {
        
        NSMutableDictionary *bigDic = [result objectForKey:@"data"];
        NSMutableArray *array = [bigDic objectForKey:@"list"];
        
        for (NSMutableDictionary *dic in array) {
            
            TOSearchDetailModel *searchDetail = [[TOSearchDetailModel alloc] init];
            [searchDetail setValuesForKeysWithDictionary:dic];
            [self.searchListArray addObject:searchDetail];
            
        }
        [self.searchTableView reloadData];
        
    } failure:^(NSError *error) {
        
        
    }];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
